package com.briup.bookstore.service.impl;

import com.briup.bookstore.common.exception.CustomException;
import com.briup.bookstore.common.response.ResultCode;
import com.briup.bookstore.common.util.ObjectUtil;
import com.briup.bookstore.dao.UserDao;
import com.briup.bookstore.common.model.entity.User;
import com.briup.bookstore.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 业务逻辑层实现类 - 认证模块
 * @author YuYan
 * @date 2023-12-22 16:14:00
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    /**
     * 用户模块Dao层对象
     */
    private final UserDao userDao;

    @Override
    public void login(User userParam) {
        /* 校验参数 */
        String username = userParam.getUsername();
        String password = userParam.getPassword();
        if (ObjectUtil.anyNotHasText(username, password)) {
            throw new CustomException(ResultCode.PARAM_NOT_COMPLETE);
        }

        /* 调用Dao层，根据username查询用户信息 */
        User record = userDao.selectByUsername(username);

        /* 登录业务逻辑处理 */
        // 1、如果用户不存在，则抛出异常
        if (ObjectUtil.isNull(record)) {
            throw new CustomException(ResultCode.USER_USERNAME_NOT_EXIST);
        }
        // 2、如果密码错误，则抛出异常
        if (ObjectUtil.notEquals(password, record.getPassword())) {
            throw new CustomException(ResultCode.USER_PASSWORD_ERROR);
        }
        // 3、如果用户状态被禁用，则抛出异常（1-禁用，0-可用）
        if (record.getStatus().equals(1)) {
            throw new CustomException(ResultCode.USER_STATUS_FORBIDDEN);
        }
        /* 通过认证，登录成功 */
    }
}
